#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>

#define MAXSIZE 4096

int main(int argc, char** argv)
{
    int sock;
    char buffer[MAXSIZE] = {0};
    char recvbuff[MAXSIZE] = {0};
    struct sockaddr_in servaddr;

    if (argc != 3) {
        printf("usage: %s <ipaddress> <port>\n", argv[0]);
        exit(0);
    }

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){
        printf("create socket error: %s\n", strerror(errno));
        exit(0);
    }

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(atoi(argv[2]));
    if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0) {
        printf("inet_pton error for %s\n", argv[1]);
        exit(0);
    }

    if (connect(sock, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0) {
        printf("connect error: %s\n",strerror(errno));
        exit(0);
    }

    // LEN(uint)+CMD(ushort)+BODY(binary)
    char *content = "who am i?";
    *((unsigned int*)buffer) = htonl(4+2+strlen(content));
    *((unsigned short*)buffer + 2) = htons(101);
    strncpy(buffer + 6, content, strlen(content));
    int length = 6 + strlen(content);

    if (send(sock, buffer, length, 0) < 0) {
        printf("send msg error: %s\n", strerror(errno));
        exit(0);
    }

    if (recv(sock, recvbuff, MAXSIZE, 0) < 0) {
        printf("recv msg error: %s\n", strerror(errno));
        exit(0);
    }

    printf("%s", recvbuff);

    close(sock);
    return 0;
}
